<template>
  <div>
    <Form
      :label-width="130"
      ref="formData"
      :model="formData"
      class="form"
      :rules="formrules"
    >
      <FormItem label="上传类别：" prop="tagIds" class="typeName">
        <Row>
          <Col span="10">
            <Select
              v-model="formData.tagIds"
              style="width: 200px"
              placeholder="请选择上传类别"
              filterable
              :only-filter-with-text="true"
              @on-change="selectChange"
            >
              <Option
                v-for="item in typeList"
                :value="item.id"
                :key="item.id"
                >{{ item.name }}</Option
              >
            </Select>
          </Col>
          <Col span="12"
            ><Button type="primary" @click="changetype">类别管理</Button></Col
          >
        </Row>
      </FormItem>
      <div class="upbox">
        <Button
          type="primary"
          size="large"
          @click="saveUpload(formData)"
          :loading="saveLoading"
          v-hasC="{
            name: 'v1-base-file-update-file-temp',
            flag: 'v1/base/file/update-file-temp',
          }"
          >开始上传</Button
        >
      </div>
      <Divider dashed />
      <div>
        <div
          class="demo-upload-list"
          v-for="(item, index) in uploadList"
          :key="index"
        >
          <template v-if="item">
            <img :src="item" width="100%" height="350px" />
            <div class="demo-upload-list-cover">
              <Icon
                type="ios-eye-outline"
                @click.native="handleView(item)"
              ></Icon>
              <Icon
                type="ios-trash-outline"
                @click.native="handleRemove(item)"
              ></Icon>
            </div>
          </template>
          <template v-else>
            <Progress
              v-if="showProgress"
              :percent="percentage"
              hide-info
            ></Progress>
          </template>
        </div>
        <Upload
          ref="upload"
          multiple
          :format="['jpg', 'png', 'gif', 'jpeg', 'webp']"
          :action="requestAction"
          :before-upload="beforeUpLoad"
          :on-progress="onprogress"
          :on-success="(res) => upSuccess(res)"
          :on-remove="(res) => upRemove(res)"
          :on-error="upError"
          :show-upload-list="false"
          type="drag"
        >
          <div style="padding: 20px 0">
            <Icon
              type="ios-cloud-upload"
              size="52"
              style="color: #3399ff"
            ></Icon>
            <p>点击或拖动上传图片，支持多图上传</p>
          </div>
        </Upload>
      </div>
    </Form>
    <!--类别管理  -->
    <Modal
      v-model="modalstatus"
      title="类别管理"
      width="600"
      footer-hide
      :mask-closable="false"
    >
      <div
        style="
          display: flex;
          justify-content: space-between;
          margin-bottom: 20px;
        "
      >
        <Input
          placeholder="请输入要搜索的类别"
          v-model="params.name"
          @on-change="changeInput"
          style="width: 200px"
        />
        <Button
          type="primary"
          @click="handleAllocation(-1)"
          v-hasC="{
            name: 'v1-base-category-update-category',
            flag: 'v1/base/category/update-category',
          }"
          >新增</Button
        >
      </div>
      <Table
        :columns="columns"
        :data="tableData"
        highlight-row
        :loading="tableloading"
      >
        <template #action="{ row, index }">
          <a
            @click="handleAllocation(row)"
            v-hasC="{
              name: 'v1-base-category-update-category2',
              flag: 'v1/base/category/update-category',
            }"
            >编辑</a
          >
          <Divider
            v-hasC="{
              name: 'v1-base-category-delete-category',
              flag: 'v1/base/category/delete-category',
            }"
            type="vertical"
          />
          <a
            @click="handleDelete(row)"
            v-hasC="{
              name: 'v1-base-category-delete-category',
              flag: 'v1/base/category/delete-category',
            }"
            >删除</a
          >
        </template>
      </Table>

      <div class="ivu-mt" style="display: flex; justify-content: center">
        <Page
          show-total
          show-elevator
          show-sizer
          :total="total"
          :current.sync="params.page"
          :page-size="params.pageSize"
          :page-size-opts="pageOpts"
          @on-change="formSize"
          @on-page-size-change="formChangePage"
        />
      </div>
    </Modal>
    <!-- 添加类别-->
    <Modal
      v-model="modaltype"
      :title="titleName"
      width="500"
      @on-cancel="canceledit"
      :mask-closable="false"
    >
      <Form
        ref="modalLine"
        :model="modalForm"
        :rules="rules"
        :label-width="100"
      >
        <FormItem label="类别名称：" prop="tags_name">
          <Input
            v-model="modalForm.tags_name"
            placeholder="请添加类别"
            maxlength="10"
            style="width: 200px"
          />
        </FormItem>
      </Form>
      <template #footer class="footer">
        <Button @click="canceledit">取消</Button>
        <Button type="primary" :loading="subloading" @click="submitedit"
          >保存</Button
        >
      </template>
    </Modal>
    <!-- 删除 -->
    <Modal
      v-model="modaldel"
      title="删除提醒"
      @on-cancel="cancel"
      width="420"
      :mask-closable="false"
    >
      <p>确定要删除当前类别？</p>
      <template #footer>
        <Button type="error" :loading="modal_loading" @click="del"
          >确定删除</Button
        >
        <Button @click="cancel">取消</Button>
      </template>
    </Modal>
    <Modal title="图片" v-model="imgVisible">
      <img :src="viewingImg" v-if="imgVisible" style="width: 100%" />
    </Modal>
  </div>
</template>
<script>
// import { materialtype, catesAdd, saveImgupload,materialtagsList,tagscatesEdit,tagscatesDelete } from '@/api/myuplod.js'
import Setting from '@/setting'
import util from '@/libs/util'
import { categoryIndex, updateCategory, deleteCategory, updatefileTemp } from '@/api/set'
export default {
  data () {
    return {
      tmpId: null,
      modalLine: 'modalLine',
      // project: util.storage.get('currentProject'),
      auth_access_token: util.cookies.get('token'),
      baseUrl: Setting.request.apiBaseURL,
      url: '',
      formData: {
        linkUrl: 0,
        tagIds: ''
      },
      formrules: {
        // tagIds: [{ required: false, message: '请选择类别', trigger: 'change' }]
      },
      requestAction: '',
      requestHeaders: {},
      typeList: [],
      file: null,
      loadingStatus: false,
      imgList: [],
      uploadList: [], // 缩略图
      // imgurl: '@/assets/images/logo-small.png',
      modalForm: {
        tags_name: '',
        id: '',
      },
      rules: {
        tags_name: [{ required: true, message: '请添加类别', trigger: 'blur' }]
      },
      modalstatus: false,
      modaltype: false,
      subloading: false,
      saveLoading: false,
      imgVisible: false,
      percentage: 0,
      showProgress: false,
      viewingImg: '',
      columns: [
        {
          title: 'ID',
          width: 60,
          key: 'id',
        },
        {
          title: '类别名称',
          minWidth: 100,
          key: 'name',
        },
        {
          title: '操作',
          width: 140,
          slot: 'action'
        }
      ],
      tableData: [],
      tableloading: false,
      titleName: '',
      params: { name: '', page: 1, pageSize: 10 },
      total: 0,
      pageOpts: [10, 20, 50, 100], // 分页每页数量
      modaldel: false,
      id: '',
      modal_loading: false,
      imageId: [],//上传的图片id
    }
  },
  created () {
    // this._gettype()
    // this.getmaterialtagsList()
  },
  mounted () {
    this.requestAction = this.baseUrl + `/v1/upload/images?auth_access_token=${util.cookies.get('token')}&auth_project_id=${localStorage.getItem('currentProject')}`
  },
  methods: {
    selectChange (val) {
      this.tmpId = val
    },
    initial () {
      this.getmaterialtagsList()
      this.formData.tagIds = ''
      this.formData.linkUrl = 0
      this.uploadList = []
    },
    // 获取类别
    // _gettype () {
    //     categoryIndex({}).then(res => {
    //         this.typeList = res;
    //     }).catch(() => {
    //         // this.tableLoading = false
    //     })
    // },
    // 添加类别
    changetype () {
      this.modalForm.tags_name = ''
      this.modalstatus = true
    },
    changeInput () {
      this.getmaterialtagsList()
    },
    /* @函数功能: 分页 */
    formSize (e) {
      this.params.page = e
      this.getmaterialtagsList()
    },
    /* @函数功能: 每页数量 */
    formChangePage (e) {
      this.params.pageSize = e
      this.getmaterialtagsList()
    },
    //获取modal列表数据
    getmaterialtagsList () {
      this.tableloading = true
      categoryIndex(this.params).then(res => {
        this.tableData = res.list
        this.typeList = res.list.map(item => ({
          id: item.id,
          name: item.name
        }))
        this.total = res.total
        this.tableloading = false
      })
    },
    //新增、编辑
    handleAllocation (row) {
      if (row === -1) {
        this.titleName = '新增类别'
      } else {
        this.titleName = '编辑类别'
        this.modalForm.tags_name = row.name
        this.modalForm.id = row.id
      }
      this.modaltype = true
    },
    // 删除接口
    handleDelete (row) {
      this.modaldel = true
      this.id = row.id
    },
    cancel () {
      this.id = null
      this.modaldel = false
      this.modal_loading = false
      this.getmaterialtagsList()
    },
    del () {
      this.modal_loading = true
      deleteCategory({ id: this.id }).then(() => {
        this.$Message.success('删除成功')
        this.cancel()
      }).catch(()=>{
        this.modal_loading = false
      })
    },
    canceledit () {
      this.$refs.modalLine.resetFields()
      this.modaltype = false
      this.subloading = false
    },
    // 类别确定
    submitedit () {
      this.$refs.modalLine.validate((valid) => {
        if (valid) {
          this.subloading = true
          if (this.titleName === '新增类别') {
            updateCategory({ name: this.modalForm.tags_name }).then(res => {
              this.$Message.success('添加成功')
              this.canceledit()
              this.getmaterialtagsList()
            }).catch(() => {
              this.canceledit()
            })
          } else {
            updateCategory({ id: this.modalForm.id, name: this.modalForm.tags_name }).then(res => {
              this.$Message.success('编辑成功')
              this.canceledit()
              this.getmaterialtagsList()
            }).catch(() => {
              this.canceledit()
            })
          }

        } else {
          // this.$Message.error('请完善表格。');
        }
      })
    },
    handleView (item) {
      // console.log(item);
      this.viewingImg = item
      this.imgVisible = true
    },
    handleRemove (item) {
      this.$Modal.confirm({
        title: '提示',
        content: '确定删除文件?',
        onOk: () => {
          this.uploadList.splice(this.uploadList.indexOf(item), 1)
          // this.imgList.splice(this.uploadList.indexOf(item), 1)
        }
      })
    },
    // 提交数据
    saveUpload (formData) {
      this.saveLoading = true
      updatefileTemp({
        id: this.imageId,
        category_id: this.tmpId
      }).then(res => {
        this.$Message.success('上传成功')
        this.saveLoading = false
        this.formData.tagIds = ''
        this.imageId = []
        this.uploadList = []
      }).catch(() => {
        this.saveLoading = false
      })
    },
    // handleUpload (file) {
    //     this.file = file;
    //     return false;
    // },
    // upload () {
    //     this.loadingStatus = true;
    //     setTimeout(() => {
    //         this.file = null;
    //         this.loadingStatus = false;
    //         this.$Message.success('Success')
    //     }, 1500);
    // },
    upRemove (res) {
      // console.log(res, 'splice')
      // this.imgList.splice
    },
    // 上传成功前
    beforeUpLoad (file) {
      //
      if ((file.type !== 'image/png') && (file.type !== 'image/jpeg') && (file.type !== 'image/jpg')) {
        this.$Message.error({
          content: '请上传 jpg/jpeg 或 png 格式的图片',
          duration: 5,
          closable: true
        })
        return false
      }
    },
    // 上传中
    onprogress (event, file, fileList) {
      this.percentage = Math.round(event.loaded * 100 / event.total)
    },
    // 上传成功后
    upSuccess (response) {
      // debugger
      // console.log(file)
      // let url = response.data.map(item => item.img_url)
      // this.imgList.push(url)
      // let imgurl = `${this.baseUrl}/library_image_tmp${url}`

      // this.uploadList.push({ imgurl: imgurl })
      this.imageId.push(response.data.image_id[0])
      const url = []
      response.data.image_url.forEach(e => {
        url.push(e)
        this.uploadList.push(`${response.data.host}${e}`)
      })
      // this.infoData.path=url,
      this.percentage = 0
    },
    // 上传失败
    upError (event, file, fileList) {
      //
    }

  }
}
</script>
<style scoped>
.form {
  position: relative;
}
.upbox /deep/.ivu-btn-primary {
  position: absolute;
  right: 40px;
  top: 20px;
}
.demo-upload-list {
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}
.demo-upload-list img {
  width: 100%;
  height: 100%;
}
.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}
.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}
.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
.typeName {
  margin-bottom: 50px;
}
/* .typeName::before{
    content: '*';
    color:#f00;
    font-size: 16px;
    position: absolute;
    top: 25%;
    left:42px;
} */
</style>
